package com.bdqn.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * DOM4J操作XML
 *
 * @author LILIBO
 * @since 2024/6/28
 */
public class Test06XmlDOM4J {

    public static void main(String[] args) {
        String xmlFile = "src/main/java/收藏信息.xml";
        SAXReader reader = new SAXReader();
        try {
            // 读取XML文件
            Document document = reader.read(xmlFile);
            // 获得根元素
            Element root = document.getRootElement();
            // 通过标签名获取根元素内的子元素
            Element brand = root.element("Brand");
            // 获取元素属性
            String name = brand.attribute("name").getValue();
            System.out.println("Brand元素的属性：name=" + name);

            List<Element> typeList = brand.elements("Type");
            for (Element element : typeList) {
                String typeName = element.attribute("name").getValue();
                System.out.println("\tType元素的属性：name=" + typeName);
            }

            // 添加元素
            Element newTypeElement = brand.addElement("Type");
            newTypeElement.addAttribute("name", "P80");

            // 保存XML
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            XMLWriter xmlWriter = new XMLWriter(new FileWriter(xmlFile), format);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (DocumentException | IOException e) {
            e.fillInStackTrace();
        }
    }

}
